package com.eclipse.training.listeners;

import java.util.ArrayList;
import java.util.Iterator;

import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.swt.dnd.DragSourceEvent;
import org.eclipse.swt.dnd.DragSourceListener;

import com.eclipse.training.model.AbstractUniverseElement;
import com.eclipse.training.ui.ElementsArrayDataTransfer;

public class TableDragSourceListener implements DragSourceListener {

	private TableViewer tableViewer;

	public TableDragSourceListener(TableViewer tableViewer) {
		this.tableViewer = tableViewer;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.eclipse.swt.dnd.DragSourceListener#dragStart(org.eclipse.swt.dnd.
	 * DragSourceEvent)
	 */
	@Override
	public void dragStart(DragSourceEvent event) {
		StructuredSelection selection = (StructuredSelection) tableViewer
				.getSelection();
		if (!selection.isEmpty()) {
			if (selection.getFirstElement() instanceof AbstractUniverseElement)
				event.doit = true;
			else
				event.doit = false;
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.eclipse.swt.dnd.DragSourceListener#dragSetData(org.eclipse.swt.dnd
	 * .DragSourceEvent)
	 */
	@SuppressWarnings("rawtypes")
	@Override
	public void dragSetData(DragSourceEvent event) {
		StructuredSelection selection = (StructuredSelection) tableViewer
				.getSelection();
		ArrayList<AbstractUniverseElement> data = new ArrayList<AbstractUniverseElement>();

		if (ElementsArrayDataTransfer.getInstance().isSupportedType(
				event.dataType)) {

			Iterator it = selection.iterator();

			while (it.hasNext())
				data.add((AbstractUniverseElement) it.next());

			event.data = data.toArray(new AbstractUniverseElement[data.size()]);
		}
	}

	@Override
	public void dragFinished(DragSourceEvent event) {
	}

}
